import 'package:dio/dio.dart';
import 'package:flutter_base_library/utils/sputils.dart';

class TokenInterceptor extends InterceptorsWrapper {
  String _token;

  @override
  onRequest(RequestOptions options) async {
    //授权码
    if (_token == null) {
      var authorizationCode = await SPUtils.getTokenStr();
      if (authorizationCode != null) {
        _token = authorizationCode;
      }
    }
    options.headers["Authorization"] = _token;
    return options;
  }

  @override
  onResponse(Response response) async {
    try {
      //如果请求Url 包含 login
      // 根据具体情况自定义.
      if (response.request.path.contains("login") == true) {
        var responseJson = response.data;
        if (response.statusCode == 200 && responseJson["token"] != null) {
          _token = 'token ' + responseJson["token"];
          await SPUtils.saveTokenStr(_token);
        }
      }
    } catch (e) {
      print(e);
    }
    return response;
  }

  ///清除授权
  clearAuthorization() {
    this._token = null;
    SPUtils.removeTokenStr();
  }
}
